<style scoped lang="scss">
::v-deep.el-table .cell {
  line-height: 40px;
  height: 40px;
}
::v-deep.el-table td,
.el-table th {
  padding: 8px 0px;
}
.dialog__body {
  background-color: #f3f3fa;
  border: 1px solid #bbbbbb;
  height: 65vh;
  overflow-y: auto;
  position: relative;
  display: flex;
  flex-direction: column;
}

.button-group {
  margin: 20px 0 0 10px;
  display: flex;
  justify-content: flex-end;

  &__info {
    margin-right: 10px;
  }
}

.tab-group {
  margin: 10px 0 0 0;
  height: 100%;

  ::v-deep .el-aside {
    padding: 10px 0 0 10px;
  }

  ::v-deep .el-input {
    padding-bottom: 10px;
  }

  ::v-deep .el-tree {
    height: var(--tree-height);
    overflow-y: auto;
  }

  ::v-deep .el-main {
    padding: 10px 10px 0 10px;
  }
}

::v-deep .el-table th.is-leaf {
  background-color: #ffffff !important;
}

.button-group__footer {
  display: flex;
  flex-direction: row-reverse;
  margin: 20px 10px 10px 0;
  //position: absolute;
  //bottom: 5px;
  //right: 0;
  &__cancel {
    margin: 0 0 0 10px;
  }
}
.explain-block {
  div {
    font-weight: 700;
    font-size: 14px;
  }
  p {
    margin: 5px;
    font-size: 12px;
    text-indent: 2em;
  }
}
</style>
<template>
  <div class="dialog__body">
    <div class="button-group">
      <el-popover placement="right" width="200" trigger="click">
        <div class="explain-block">
          <div>功能：</div>
          <p>{{ explainData.funDescription }}</p>
          <div>输入端口：</div>
          <p>{{ explainData.inPort }}</p>
          <div>输出端口：</div>
          <p>{{ explainData.outPort }}</p>
          <div>参数：</div>
          <p>{{ explainData.functionName }}</p>
        </div>
        <mine-button
          slot="reference"
          type="primary"
          class="button-group__info"
          @click="getExplainInfo('missing')"
          ><i class="iconfont icon-help-circle-line"></i>说明</mine-button
        >
      </el-popover>
    </div>
    <div class="tab-group">
      <el-container>
        <el-aside width="200px">
          <!-- <el-input
            placeholder="请输入字段名"
            suffix-icon="el-icon-search"
            v-model="searchInput"
          >
          </el-input> -->
          <el-tree
            :data="dataList"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :style="cssVars"
          ></el-tree>
        </el-aside>
        <el-main>
          <el-form ref="formRef" :model="form" :rules="form.rules">
            <el-table
              class="table border-table"
              :data="form.tableData"
              style="width: 100%"
              v-loading="loading"
              :height="tableHeight"
              ref="multipleTable"
              :row-style="{ height: 40 + 'px' }"
            >
              <el-table-column label="字段名" prop="name" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="type" label="类型" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="missing" label="处理方式">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'tableData[' + scope.$index + '].missing'"
                    :rules="form.rules.missing"
                  >
                    <el-select
                      v-model="scope.row.missing"
                      placeholder="请选择"
                      size="small"
                    >
                      <el-option
                        v-for="item in scope.row.conditionSelection"
                        :key="item.optCode"
                        :label="item.optName"
                        :value="item.optCode"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="值/字段" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-input
                    size="small"
                    :disabled="scope.row.missing != 'custom'"
                    v-model="scope.row.value"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" show-overflow-tooltip>
                <template slot-scope="scope">
                  <mine-button type="delete" @click="detectRow(scope.row)"
                    >移除</mine-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <!--                    <mine-pagination-->
          <!--                        @numberChange="numberChange"-->
          <!--                        :total="total"-->
          <!--                        :page-size="pageSize"-->
          <!--                        :current-page="currentPage">-->
          <!--                    </mine-pagination>-->
        </el-main>
      </el-container>
    </div>
    <div class="button-group__footer">
      <mine-button
        type="primary"
        secondary
        class="button-group__footer__cancel"
        @click="close"
        >取消</mine-button
      >
      <mine-button type="primary" @click="confirm">确定</mine-button>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  name: "filterOpera",
  props: {
    currentOperatorData: {
      type: Object,
    },
    fileDataList: {
      type: Array,
    },
    missingConditionSelectionList: {
      type: Array,
    },
  },
  data() {
    return {
      loading: false,
      // tableData: [],
      searchInput: "",
      dataList: JSON.parse(JSON.stringify(this.fileDataList)),
      defaultProps: {
        children: "children",
        label: "name",
      },
      form: {
        tableData: [],
        rules: {
          missing: [
            {
              required: true,
              message: "请选择",
            },
          ],
        },
      },
      explainData: {}, // 说明数据
    };
  },
  computed: {
    tableHeight: function () {
      return 0.5 * window.innerHeight + "px";
    },
    cssVars() {
      return {
        "--tree-height": 0.4 * window.innerHeight - 50 + "px",
      };
    },
  },
  methods: {
    async getExplainInfo(type) {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/helpInfo/getTree?helpCode=${type}`,
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {},
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.explainData = result?.data;
            } else {
              _self.$message.warning("获取说明信息失败！");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/helpInfo/getTree?helpCode=${type}`,
          "get",
          "application/json;charset=UTF-8",
          {},
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.explainData = res?.data;
            } else {
              this.$message.warning("获取说明信息失败！");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getOperatorExplain", type);
        if (res.data.success) {
          this.explainData = res.data?.data;
        } else {
          this.$message.warning("获取说明信息失败！");
        }
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleNodeClick(data) {
      // 移除当前点击的数据
      this.dataList = this.dataList.filter((item) => {
        if (data.id === item.id) {
          return false;
        }
        return true;
      });
      // 根据类型拿到过滤条件的下拉选项
      const findSelection = this.missingConditionSelectionList.find((item) => {
        if (data.type === item.dirCode.split("_")[1]) {
          return true;
        }
        return false;
      });
      data.conditionSelection = findSelection.childrenParams;
      data.missingType = data.type;
      data.datafieldId = data.id;
      // 添加到右边表格
      this.form.tableData.push(data);
    },
    close() {
      this.$emit("changeFlag");
    },
    // 当前行的删除
    detectRow(row) {
      // 移除当前点击的数据
      this.form.tableData = this.form.tableData.filter((item) => {
        if (row.id === item.id) {
          return false;
        }
        return true;
      });
      // 添加到左边表格
      this.dataList.push(row);
    },
    // 确定按钮
    async confirm() {
      // 表格中的表单校验，通过才放行
      await this.$refs.formRef.validate();

      this.form.tableData = this.form.tableData.map((item) => {
        return Object.assign(item, {
          processingId: this.currentOperatorData.id,
        });
      });
      let params = {
        key: "processingId",
        value: this.currentOperatorData.id,
        t: this.form.tableData,
      };
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/feMissingRule/saveOrUpdateBatchBfClear?key=${params.key}&value=${params.value}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: params.t,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.$message.success("保存成功");
              _self.close();
            } else {
              _self.$message.error("保存失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/feMissingRule/saveOrUpdateBatchBfClear?key=${params.key}&value=${params.value}`,
          "post",
          "application/json;charset=UTF-8",
          params.t,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.$message.success("保存成功");
              this.close();
            } else {
              this.$message.error("保存失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("postMissing", params);
        if (res.status === 200) {
          this.$message.success("保存成功");
          this.close();
        } else {
          this.$message.error("保存失败");
        }
      }
    },
    // 根据算子id获取右边表格数据
    async getMissingTableByOperatorId() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/feMissingRule/list",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                { processingId: _self.currentOperatorData.id },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              // 根据类型拿到过滤条件的下拉选项
              result.data.forEach((ele) => {
                _self.missingConditionSelectionList.forEach((item) => {
                  if (ele.type === item.dirCode.split("_")[1]) {
                    ele.conditionSelection = item.childrenParams;
                  }
                });
              });
              // 匹配字段名并赋值name
              result.data.forEach((item) => {
                _self.dataList.forEach((ele) => {
                  if (item.id === ele.id) {
                    item.name = ele.name;
                  }
                });
              });
              // 根据右边回显列表过滤掉左边的列表
              _self.dataList = _self.dataList.filter((item) => {
                for (let i = 0; i < result.data.length; i++) {
                  if (item.id === result.data[i].id) {
                    return false;
                  }
                }
                return true;
              });
              _self.form.tableData = result.data;
            } else {
              _self.$message.error("获取缺省值处理列表数据失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/feMissingRule/list",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            { processingId: this.currentOperatorData.id },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            console.log(res);
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              // 根据类型拿到过滤条件的下拉选项
              res.data.forEach((ele) => {
                this.missingConditionSelectionList.forEach((item) => {
                  if (ele.type === item.dirCode.split("_")[1]) {
                    ele.conditionSelection = item.childrenParams;
                  }
                });
              });
              // 匹配字段名并赋值name
              res.data.forEach((item) => {
                this.dataList.forEach((ele) => {
                  if (item.id === ele.id) {
                    item.name = ele.name;
                  }
                });
              });
              // 根据右边回显列表过滤掉左边的列表
              this.dataList = this.dataList.filter((item) => {
                for (let i = 0; i < res.data.length; i++) {
                  if (item.id === res.data[i].id) {
                    return false;
                  }
                }
                return true;
              });
              this.form.tableData = res.data;
            } else {
              this.$message.error("获取缺省值处理列表数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch(
          "getMissingTableByOperatorId",
          this.currentOperatorData.id
        );
        if (res.data.status === 200) {
          // 根据类型拿到过滤条件的下拉选项
          res.data.data.forEach((ele) => {
            this.missingConditionSelectionList.forEach((item) => {
              if (ele.type === item.dirCode.split("_")[1]) {
                ele.conditionSelection = item.childrenParams;
              }
            });
          });
          // 匹配字段名并赋值name
          res.data.data.forEach((item) => {
            this.dataList.forEach((ele) => {
              if (item.id === ele.id) {
                item.name = ele.name;
              }
            });
          });
          // 根据右边回显列表过滤掉左边的列表
          this.dataList = this.dataList.filter((item) => {
            for (let i = 0; i < res.data.data.length; i++) {
              if (item.id === res.data.data[i].id) {
                return false;
              }
            }
            return true;
          });
          this.form.tableData = res.data.data;
        } else {
          this.$message.error("获取缺省值处理列表数据失败");
        }
      }
    },
  },
  created() {
    // setTimeout(() => {
    this.getMissingTableByOperatorId();
    // }, 200);
  },
};
</script>
